package com.course.file.controller.admin;

import com.course.server.dto.FileDto;
import com.course.server.dto.ResponseDto;
import com.course.server.enums.FileUseEnum;
import com.course.server.service.FileService;
import com.course.server.utils.UuidUtil;
import io.swagger.annotations.Api;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Locale;

/**
 * 〈一句话功能简述>
 * 〈讲师头像上传〉
 *
 * @Author 17505
 * @Create 2021/7/17
 * @Since 1.0.0
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "图片上传")
public class UploadController {

    private static final Logger LOG = LoggerFactory.getLogger(UploadController.class);
    public static final String BUSINESS_NAME = "上传文件";

    @Value("${file.domain}")
    private String FILE_DOMAIN;
    
    @Value("${file.path}")
    private String FILE_PATH;

    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    public ResponseDto <FileDto> upload(@RequestParam MultipartFile file,String
                                        use) throws IOException {
        ResponseDto <FileDto> result = new ResponseDto <>();
        LOG.info(file.getOriginalFilename());
        LOG.info(String.valueOf(file.getSize()));
        // 保存文件到本地
        FileUseEnum fileUseEnum = FileUseEnum.getByCode(use);
        String key = UuidUtil.getShortUuid();
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //  如果文件夹不存在则创建
        String dir = fileUseEnum.name().toLowerCase();
        File fullDir = new File(FILE_PATH + dir);
        if (!fullDir.exists()) {
            fullDir.mkdirs();
        }
        String path = dir + File.separator + key + "." + suffix;
        String fullPath =FILE_PATH  + path;
        File dest = new File(fullPath);
        file.transferTo(dest);
        LOG.info(dest.getAbsolutePath());
        LOG.info("保存文件记录开始");
        FileDto fileDto = new FileDto();
        fileDto.setPath(path);
        fileDto.setName(fileName);
        fileDto.setSize(Math.toIntExact(file.getSize()));
        fileDto.setUse(fileUseEnum.getCode());
        fileDto.setSuffix(suffix);
        fileService.save(fileDto);
        fileDto.setPath(FILE_DOMAIN + path);
        result.setContent(fileDto);
        return result;
    }

}